package com.mszlu.rpc.register.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.remote.client.RpcClient;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.List;
@Slf4j

public class NacosTemplate {

    private ConfigService configService;//主要用作配置方面的管理功能
    private NamingService namingService;//主要用作服务方面的管理功能

//初始化namingService和configService;
    public NacosTemplate(){
        try {
//             configService = NacosFactory.createConfigService("localhost:8848");
             namingService = NacosFactory.createNamingService("localhost:8848");
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
    
//注册服务
    public void registerServer(Instance instance) throws Exception{
        namingService.registerInstance(instance.getServiceName(),instance);
    }

    //注册服务
    public void registerServer(Instance instance, String groupName) throws Exception{
        while (!isNacosConnected()) {
            System.out.println("⏳ 等待 Nacos 服务...");
            Thread.sleep(500);
        }
        namingService.registerInstance(instance.getServiceName(), groupName, instance);
    }

    // 在 NacosTemplate.java 中加一个方法
    public boolean isNacosConnected() {
        try {
            // 调用一个轻量级 API，比如获取服务列表
            namingService.getServicesOfServer(1, 1, "DEFAULT_GROUP");
            System.out.println("✅ Nacos 连接正常");
            return true;
        } catch (Exception e) {
            System.out.println("❌ Nacos 连接异常: " + e.getMessage());
            return false;
        }
    }

//删除服务
    public void deleteServer(Instance instance) throws Exception{
        namingService.deregisterInstance(instance.getServiceName(),instance.getIp(),instance.getPort());
    }

    //随机全部（有可能获取到的不健康）。拿到全部实例后，我们可以按照自己的负载均衡算法进行调用。类似于springcloud的ribbon。
    public List<Instance> getAllServer(String serverName) throws Exception{
        return namingService.getAllInstances(serverName);
    }

    //根据负载均衡算法获取一个健康的实例
    public Instance getOneHealthyInstance(String serverName, String groupName) throws Exception{
        return namingService.selectOneHealthyInstance(serverName, groupName);
    }

    public void init(String host, int port) {
//        printNacosClientStatus();
        try {
//            configService = NacosFactory.createConfigService("localhost:8848");
//            System.out.println(host);
//            System.out.println(port);
//            System.out.println(host+":"+port);
            namingService = NacosFactory.createNamingService(host+":"+port);
//            namingService = NacosFactory.createNamingService("localhost:8848");
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

}
